package com.duckygo.towerdefense.game.sprites;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import java.nio.ShortBuffer;

import javax.microedition.khronos.opengles.GL10;

import android.util.Log;

import com.duckygo.towerdefense.game.TextureManager;
import com.duckygo.towerdefense.game.scenes.TowerDefenseScene;

public class Terrain3DSprite extends Sprite {

	private IntBuffer vertexBuffer;

	private ShortBuffer indexBuffer;

	private IntBuffer textureBuffer;
	
	
	public float x;
	
	public float y;
	
	public float rotation;

	public Terrain3DSprite() {
		int vertices[] = {
			      -0x10000,  0x10000, 0, 
			      -0x10000, -0x10000, 0, 
			      0x10000, -0x10000, 0, 
			      0x10000,  0x10000, 0, 
			};
		
		 int texture[] = {    		
		    		0, 0,
		    		0, 0x10000,
		    		0x10000, 0x10000,
		    		0x10000, 0,
		 };
		

		short[] indices = { 0, 1, 2, 0, 2, 3 };
		

		
		
		ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length * 4);
		vbb.order(ByteOrder.nativeOrder());
		vertexBuffer = vbb.asIntBuffer();
		vertexBuffer.put(vertices);
		vertexBuffer.position(0);

		ByteBuffer ibb = ByteBuffer.allocateDirect(indices.length * 2);
		ibb.order(ByteOrder.nativeOrder());
		indexBuffer = ibb.asShortBuffer();
		indexBuffer.put(indices);
		indexBuffer.position(0);
	 
		ByteBuffer tbb = ByteBuffer.allocateDirect(texture.length * 4);
		tbb.order(ByteOrder.nativeOrder());
		textureBuffer = tbb.asIntBuffer();
		textureBuffer.put(texture);
		textureBuffer.position(0);		
		
		
		
	}
	
	
	
	
	@Override
	public void draw(GL10 gl) {
		//Log.w("Terrain3DSprite", "Drawing terrain");
		
		gl.glScalef(2f, 2f, 1f);
		
		gl.glTranslatef(x, y, 0);
		gl.glRotatef(rotation, 0, y, 0);
		
		gl.glFrontFace(GL10.GL_CCW); 
		gl.glEnable(GL10.GL_CULL_FACE);
		gl.glCullFace(GL10.GL_BACK);

		gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
		gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
		
		TextureManager.bindTexture(gl, TowerDefenseScene.TERRAIN_TEX, null);
		gl.glVertexPointer(3, GL10.GL_FIXED, 0, vertexBuffer);
		gl.glTexCoordPointer(2, GL10.GL_FIXED, 0, textureBuffer);	

		gl.glDrawElements(GL10.GL_TRIANGLES, indexBuffer.capacity(),  GL10.GL_UNSIGNED_SHORT, indexBuffer);

		gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); 
		gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
		
		gl.glDisable(GL10.GL_CULL_FACE);

	}


}
